package com.iot.web.core.config;

import com.iot.common.core.domain.entity.SysUser;
import com.iot.common.utils.SecurityUtils;
import com.iot.framework.mobile.token.LoginUserTokenHandlerMethodArgumentResolver;
import com.iot.framework.mobile.token.UserTokenManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        // 先判断是否手机用户登录
        Object token = request.getHeaders().get(LoginUserTokenHandlerMethodArgumentResolver.LOGIN_TOKEN_KEY);
        if (token != null && token.toString().isEmpty()) {
            config.getUserProperties().put("sysUser", UserTokenManager.getToken(token.toString()));
            return;
        }
        try{
//            SysUser sysUser = SecurityUtils.getSysUser();
        /*HttpSession httpSession = (HttpSession) request.getHttpSession();
        if(httpSession != null){
            config.getUserProperties().put(HttpSession.class.getName(), httpSession);
        }*/
//            if(sysUser != null){
//                config.getUserProperties().put("sysUser", sysUser);
//            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 注入ServerEndpointExporter，
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}